import JSEncrypt from 'jsencrypt';
import { Base64 } from 'js-base64';


// 创建JSEncrypt对象
const encrypt = new JSEncrypt();
// 设置MAX_ENCRYPT_BLOCK为245
// 加载私钥
const MAX_ENCRYPT_BLOCK: number = 245;
export const generator = (data: string, privateKey: string) => {
  // 假设你已经有一个JSEncrypt实例并已加载私钥 
  var encryptor = new JSEncrypt();
  encryptor.setPrivateKey(privateKey);

  const MAX_ENCRYPT_BLOCK = 245; // 这个值取决于你的密钥长度和填充方式，实际应用时需要调整为合适的大小

  function encryptByPrivateKey(data: string) {
    var encryptedData = [];
    var inputBytes = data.split('').map(c => c.charCodeAt(0));
    var blockSize = MAX_ENCRYPT_BLOCK / 8; // 按字节计算块大小

    for (var offset = 0; offset < inputBytes.length; offset += blockSize) {
      var chunk = inputBytes.slice(offset, offset + blockSize);
      var cache = encryptor.encrypt(String.fromCharCode.apply(null, chunk)); // 对当前块进行加密
      encryptedData.push(cache);
    }
    // 合并所有加密后的块，并转为Base64编码
    var concatenatedEncryptedData = encryptedData.join('');
    return btoa(concatenatedEncryptedData); // 使用浏览器内置的btoa函数或引入一个兼容性更好的Base64库
  }
  let encryptedMessage=''
  try {
    encryptedMessage = encryptByPrivateKey(data);
    console.log("encryptedMessage", encryptedMessage)
  } catch (error) {
    console.error('Error during encryption:', error);
  }
  return encryptedMessage
}

export const decodeMessage = (data: string, publicKey: string) => {
  // 假设你已经有一个JSEncrypt实例并已加载公钥
  var decryptor = new JSEncrypt();
  decryptor.setPublicKey(publicKey);

  function decryptByPublicKey(data: string) {
    var encryptedDataBytes = atob(data); // 使用浏览器内置的atob函数或引入一个兼容性更好的Base64库
    var inputLen = encryptedDataBytes.length;
    var decryptedData: any = [];

    for (let offset = 0; offset < inputLen; offset += MAX_DECRYPT_BLOCK) {
      const chunk = encryptedDataBytes.substr(offset, MAX_DECRYPT_BLOCK);
      const cache = decryptor.decrypt(chunk); // 对当前块进行解密
      console.log("cache",cache)
      if (cache) {
        decryptedData.push.apply(decryptedData, cache.split('').map(c => c.charCodeAt(0)));
      }
    }
    console.log("dataArr",decryptedData)
    // 将所有解密后的字节合并成一个Uint8Array，然后转换为字符串
    var byteArray = new Uint8Array(decryptedData);
    return new TextDecoder('utf-8').decode(byteArray);
  }
  let decryptedMessage =''
  try {
    decryptedMessage = decryptByPublicKey(data);
  } catch (error) {
    console.error('Error during decryption:', error);
  }
  return decryptedMessage
}

// 加密函数
export const encryptByPrivateKey = (data: string) => {
  // 将字符串转换为字节数组
  const encoder = new TextEncoder();
  //const dataBytes = encoder.encode(data);
  const dataBytes = new Uint8Array(Buffer.from(data, 'utf-8'))
  // 获取字节数组的长度
  const inputLen = dataBytes.length;
  let encryptedData: string = '';
  let offset: number = 0;
  let i: number = 0;

  // 对数据分段加密
  while (inputLen - offset > 0) {
    let cache: string = '';
    let cacheData: string | false;
    if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
      const chunk = data.slice(offset, offset + MAX_ENCRYPT_BLOCK);
      cacheData = encrypt.encrypt(chunk);
      if (cacheData) {
        cache = cacheData
      }
    } else {
      const remainingData = data.slice(offset);
      cacheData = encrypt.encrypt(remainingData);
      if (cacheData) {
        cache = cacheData
      }
    }
    encryptedData += cache;
    i++;
    offset = i * MAX_ENCRYPT_BLOCK;
  }
  // 返回加密后的字符串
  return encryptedData;
}


// 设置MAX_DECRYPT_BLOCK为256
const MAX_DECRYPT_BLOCK: number = 256;

// 公钥解密函数
export const decryptByPublicKey = (data: string) => {
  // 创建JSEncrypt对象
  const decrypt = new JSEncrypt();
  // 加载公钥
  //decrypt.setPublicKey(publicKey);
  const textEncoder = new TextEncoder();
  const textDecoder = new TextDecoder();
  const dataBytes: Uint8Array = Base64.toUint8Array(data);
  const inputLen: number = dataBytes.length;
  const out: Uint8Array[] = [];
  let offset: number = 0;
  let i: number = 0;

  // 对数据分段解密
  while (inputLen - offset > 0) {
    let cache: Uint8Array;
    if (inputLen - offset > MAX_DECRYPT_BLOCK) {
      const slice = dataBytes.slice(offset, offset + MAX_DECRYPT_BLOCK);
      const sliceStr = textDecoder.decode(slice);
      const decryptedSlice = decrypt.decrypt(sliceStr) as string;
      console.log("输出结果", decryptedSlice)
      const decryptedBytes = textEncoder.encode(decryptedSlice);
      cache = new Uint8Array(decryptedBytes);

    } else {
      const slice = dataBytes.slice(offset);
      const sliceStr = textDecoder.decode(slice);
      const decryptedSlice = decrypt.decrypt(sliceStr) as string;
      console.log("输出结果2", decryptedSlice)
      const decryptedBytes = textEncoder.encode(decryptedSlice);
      cache = new Uint8Array(decryptedBytes);
    }
    out.push(cache);
    i++;
    offset = i * MAX_DECRYPT_BLOCK;
  }
  // 解密后的内容
  return textDecoder.decode(new Uint8Array(out.flatMap((arr) => Array.from(arr))));
}
export const decryptByPublicKey2 = (data: string) => {
  const decrypt = new JSEncrypt();
  const result = decrypt.decrypt(data)
  // 解密后的内容
  return result;
}
export default {
  generator,
  decodeMessage,
  encryptByPrivateKey,
  decryptByPublicKey,
  decryptByPublicKey2,
}